package han.ap.vision.server.object_finder;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

import javax.imageio.ImageIO;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ObjectFinder {
	public int[][] field;
	private int x, y; // only in debug mode

	public ObjectFinder() {
		this.y = 800;
		this.x = 600;
		field = new int[y][x];
	}

	public int[][] get_field() {
		synchronized (field) {
			return field;
		}
	}

	public void fill_field(JSONArray coordinates) {
		synchronized (field) {
			clear_field();
			for (int i = 0; i < coordinates.length(); i += 2) {
				try {
					field[(Integer) coordinates.get(i + 1)][(Integer) coordinates
							.get(i)] = 1;
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	public String getResolution() {
		return this.y + " " + this.x;
	}

	private void clear_field() {
		for (int y = 0; y < field.length; y++) {
			for (int x = 0; x < field[0].length; x++) {
				field[y][x] = 0;
			}
		}
	}

	public void save_field(String filename) {
		BufferedImage image = null;
		image = new BufferedImage(800, 600, BufferedImage.TYPE_INT_RGB);
		synchronized (field) {
			for (int y = 0; y < field.length; y++) {
				for (int x = 0; x < field[0].length; x++) {
					if (field[y][x] == 1) {
						image.setRGB(x, y, 255);
					}
				}
			}
		}
		try {
			File outputfile = new File(filename);
			ImageIO.write(image, "png", outputfile);
		} catch (IOException e) {
		}
	}
}
